﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Diagnostics;
using Sitecore.Shell.Framework.Commands;
using Sitecore.Web;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.ChangesTracker.Events;
using Sitecore.Data.Templates;
using Sitecore.Data.Managers;
using Sitecore.ChangesTracker.Archiving;
using System.Web;

namespace Sitecore.ChangesTracker.Commands
{
  class Save : Command
  {
    public override void Execute(Shell.Framework.Commands.CommandContext context)
    {
      Assert.ArgumentNotNull(context, "context");
      string query = WebUtil.GetQueryString("id");
        if (string.IsNullOrEmpty(query))
        {
            query = ItemUri.Parse(HttpUtility.UrlDecode(HttpContext.Current.Request.Form["__CurrentItem"])).ItemID.ToString();
        }
        if (!string.IsNullOrEmpty(query))
      {
        ID id=null;
        if(ID.TryParse(query,out id))
        {
        Template t = TemplateManager.GetTemplate(id, Context.ContentDatabase);
        if (t == null)
        {
            Item item=Client.ContentDatabase.GetItem(id);
            if (TemplateManager.IsTemplatePart(item))
            {
                item = TemplateTracker.FindTemplate(item);
                t = TemplateManager.GetTemplate(item.ID, item.Database);
            }
                
        }
         if (t != null)
         {
           TemplateTracker.TrackTemplate(t);
         }
        }
      }
    }
  }
}
